<template>
  <div class="app-container">
    <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="110px"
      style="width: 590px; margin-left:50px;">
      <el-form-item :label="$t('Coupon_name')" prop="name">
        <el-input v-model="dataForm.name" />
      </el-form-item>

      <el-form-item :label="$t('优惠券图片')" prop="pictureUrl">
        <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadPicUrl"
          :on-remove="handleGoodsPicRemove" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
          <img v-if="dataForm.pictureUrl" :src="dataForm.pictureUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <label v-if="dataForm.pictureUrl" class="el-upload-list__item-status-label avatar-uploader__status_label"
            @click.stop="handleGoodsPicRemove()"><i class="el-icon-delete"></i></label>
        </el-upload>
      </el-form-item>
      <!--       <el-form-item :label="$t('分发类型')" prop="type">-->
      <!--         <el-select v-model="dataForm.type" >-->
      <!--           <el-option-->
      <!--             v-for="type in typeOptions"-->
      <!--             :key="type.value"-->
      <!--             :label="type.label"-->
      <!--             :value="type.value"/>-->
      <!--         </el-select>-->
      <!--       </el-form-item>-->
      <el-form-item :label="$t('折扣类型')" prop="discountType">
        <el-radio-group v-model="dataForm.discountType">
          <el-radio :label="1">{{ $t('满减') }}</el-radio>
          <el-radio :label="2">{{ $t('折扣') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="dataForm.discountType == 1" :label="$t('Discount_price')" prop="discount">
        <el-input v-model.number="dataForm.discount" type="number" min="0" oninput="if(value<0) value= (-1) * value">
          <template slot="append">{{ $t('Dollars') }}</template>
        </el-input>
      </el-form-item>
      <el-form-item v-show="dataForm.discountType == 2" :label="$t('折扣')" prop="discountRate">
        <el-input v-model.number="dataForm.discountRate" type="number" min="0"
          oninput="if(value<0) value= (-1) * value">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('Lowest_spending_value')" prop="min">
        <el-input v-model.number="dataForm.min" type="number" min="0">
          <template slot="append">{{ $t('Dollars') }}</template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('使用范围')">
        <!-- <el-radio v-model="dataForm.ranges" :label="0">{{$t('通用')}}</el-radio>
         <el-radio v-model="dataForm.ranges" :label="1">{{$t('APP')}}</el-radio>
         <el-radio v-model="dataForm.ranges" :label="2">{{$t('POS')}}</el-radio>
         <el-radio v-model="dataForm.ranges" :label="3">{{$t('网站')}}</el-radio> -->
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="0" @change="changeCheckbox">{{ $t('通用') }}</el-checkbox>
          <el-checkbox label="1" @change="changeCheckbox">{{ $t('APP') }}</el-checkbox>
          <el-checkbox label="2" @change="changeCheckbox">{{ $t('POS') }}</el-checkbox>
          <el-checkbox label="3" @change="changeCheckbox">{{ $t('网站') }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item :label="$t('Amount_of_coupons')" prop="total">
        <el-input v-model.number="dataForm.total" type="number" min="0" oninput="if(value<0) value= (-1) * value">
          <template slot="append">{{ $t('Sheets') }}</template>
        </el-input>
      </el-form-item>

      <el-form-item :label="$t('有效期')" prop="timeType">
        <el-radio-group v-model="dataForm.timeType">
          <el-radio-button v-if="dataForm.type != 3" :label="0">{{ $t('Respective_days_after_claiming_the_coupon') }}
          </el-radio-button>
          <el-radio-button :label="1">{{ $t('Select_deadline') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="dataForm.timeType === 0" prop="days">
        <el-input v-model.number="dataForm.days" type="number">
          <template slot="append">{{ $t('天') }}</template>
        </el-input>
      </el-form-item>

      <el-form-item v-show="dataForm.timeType === 1" prop="startTime">
        <el-date-picker v-model="dataForm.startTime" type="datetime" :placeholder="$t('Select_dates')"
          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" :picker-options="pickerOptions" />
      </el-form-item>
      <el-form-item v-show="dataForm.timeType === 1" prop="endTime">
        <el-date-picker v-model="dataForm.endTime" type="datetime" :placeholder="$t('Select_dates')"
          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" :picker-options="pickerOptions" />
      </el-form-item>

      <el-form-item :label="$t('商品限制范围')">
        <el-radio-group v-model="dataForm.goodsType">
          <el-radio-button :label="0">{{ $t('Usable_in_any_situation') }}</el-radio-button>
          <el-radio-button :label="1">{{ $t('指定分类') }}</el-radio-button>
          <el-radio-button :label="2">{{ $t('指定商品') }}</el-radio-button>
          <!--            <el-radio-button :label="2">{{$t('Select_merchandise')}}</el-radio-button>-->
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="dataForm.goodsType === 1" prop="goodsValue">
        <!--          {{$t('Not_supported_at_the_moment')}}-->
        <el-cascader :options="categories" :props="props" v-model="dataForm.goodsValue" :show-all-levels="false"
          collapse-tags clearable>
        </el-cascader>
      </el-form-item>

      <el-form-item v-show="dataForm.goodsType === 2" prop="detailedGoodsValue">
        <el-select multiple v-model="dataForm.selectGoods" :placeholder='$t("请选择")' collapse-tags style="width: 400px">
          <el-option v-for="item in goodsList" :key="item.key" :label="item.label" :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('区域限制')">
        <el-radio-group v-model="dataForm.areaLimit">
          <el-radio-button :label="0">{{ $t('不限区域') }}</el-radio-button>
          <el-radio-button :label="1">{{ $t('限制区域') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="dataForm.areaLimit == 0 ? false : true" prop="regions">
        <el-cascader :options="locations" :props="regionProps" v-model="dataForm.regions" :show-all-levels="false"
          collapse-tags clearable>
        </el-cascader>
      </el-form-item>

      <el-form-item :label="$t('损耗承受单位')">
        <el-radio-group v-model="dataForm.lossBearing">
          <el-radio-button :label="0">{{ $t('总部') }}</el-radio-button>
          <el-radio-button :label="1">{{ $t('门店') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('Explanation')" prop="useInstruction">
        <el-input type="textarea" v-model="dataForm.useInstruction"></el-input>
      </el-form-item>
    </el-form>
    <div class="op-container">
      <el-button @click="handleBack" style="margin-right: 480px">{{ $t('Back') }}</el-button>
      <el-button v-if="typePage" type="primary" v-permission="['GET /admin/p/coupon_exten_add']"
        @click="createData">{{ $t('Confirm') }}</el-button>
      <el-button v-else type="primary" v-permission="['GET /admin/p/coupon_exten_add']" @click="updateData">
        {{ $t('Confirm') }}</el-button>
    </div>
  </div>
</template>

<script>
import { listCategory } from '../../api/category'
import { listLocationRegion } from '../../api/region'
import { listGoods } from '../../api/goods'
import { createCoupon, updateCoupon } from '../../api/coupon'
import { uploadPath } from '../../api/storage'

export default {
  name: 'extenCouponCreate',
  data() {
    const defaultTypeOptions = [
      {
        label: this.$t('推广优惠券'),
        value: 3
      }
    ]

    const defaultStatusOptions = [
      {
        label: this.$t('Normal'),
        value: 0
      },
      {
        label: this.$t('Expired'),
        value: 1
      },
      {
        label: this.$t('Merchandise_removed'),
        value: 2
      }
    ]

    const validateDiscount = (rule, value, callback) => {
      let discountType = this.dataForm.discountType
      if (discountType == 1 && value == null) {
        return callback(new Error(this.$t('满减金额不能为空')));
      }

      callback();
    }

    const validateDiscountRate = (rule, value, callback) => {
      let discountType = this.dataForm.discountType
      if (discountType == 2 && !value) {
        return callback(new Error(this.$t('百分比不能为空')));
      }

      callback();
    }

    const validateDays = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 0 && !value) {
        return callback(new Error(this.$t('相对天数不能为空')));
      }

      callback();
    }

    const validateStartTime = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 1 && !value) {
        return callback(new Error(this.$t('开始时间不能为空')));
      }

      callback();
    }

    const validateEndTime = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 1 && !value) {
        return callback(new Error(this.$t('结束时间不能为空')));
      }

      callback();
    }

    const validateGoodsValue = (rule, value, callback) => {
      let goodsType = this.dataForm.goodsType
      if (goodsType == 1 && value.length == 0) {
        return callback(new Error(this.$t('商品分类不能为空')));
      }
      callback();
    }

    const validateRegions = (rule, value, callback) => {
      let regions = this.dataForm.regions;
      if(this.dataForm.areaLimit == 0){
        callback();
      }
      if (!regions || regions.length == 0) {
        return callback(new Error(this.$t('区域不能为空')));
      }
      callback();
    }


    return {
      uploadPath,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      dataForm: {
        selectGoods: [],
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        total: 1,
        discount: 1,
        discountType: 1,
        discountRate: 100,
        min: 1,
        ranges: 0,
        limit: 1,
        type: 3,
        status: 0,
        goodsType: 0,
        goodsValue: [],
        regions: [],
        levelMemberType: [],
        moneyMemberType: [],
        useLimit: '',
        useLimitNum: 1,
        areaLimit: 0,
        lossBearing: 0,
        timeType: 1,
        days: 1,
        startTime: null,
        endTime: null,
        userLevel: [0],
        promotionOnly: false,
        country: '',
        province: '',
        city: '',
        pictureUrl: '',
        surplus: 0,
      },
      typeOptions: Object.assign({}, defaultTypeOptions),
      dialogFormVisible: false,
      dialogStatus: '',
      list: [],
      checkList: [],
      rules: {
        name: [
          { required: true, message: this.$t('Coupon_title_cannot_be_empty'), trigger: 'blur' }
        ],
        discount: [
          { validator: validateDiscount, trigger: 'blur' }
        ],
        discountRate: [
          { validator: validateDiscountRate, trigger: 'blur' }
        ],
        min: [
          { required: true, trigger: 'blur' }
        ],
        limit: [
          { required: true, trigger: 'blur' }
        ],
        total: [
          { required: true, trigger: 'blur' }
        ],
        useLimit: [
          { required: true, trigger: 'change', message: this.$t('用户限制类型不能为空') }
        ],
        useLimitNum: [
          { required: true, trigger: 'blur' }
        ],
        timeType: [
          { required: true, trigger: 'blur' }
        ],
        days: [
          { validator: validateDays, trigger: 'blur' }
        ],
        startTime: [
          { validator: validateStartTime, trigger: 'blur' }
        ],
        endTime: [
          { validator: validateEndTime, trigger: 'blur' }
        ],
        goodsValue: [
          { validator: validateGoodsValue, trigger: 'blur' }
        ],
        regions: [
          { validator: validateRegions, trigger: 'blur' }
        ],

      },
      categories: [],
      locations: [],
      goodsList: [],
      props: { multiple: true, value: 'id', label: 'name', emitPath: false },
      regionProps: { multiple: true, value: 'id', label: 'nameEn', emitPath: false },
    }
  },
  created() {
    // console.log("进入了created方法中")
    this.init();
    this.getCategories()
    this.getLocations()
    this.getGoods()
  },
  methods: {
    changeCheckbox(val, $event) {
      const target = $event.target.value;
      if (target == 0) {
        if (val) {
          this.checkList = ['0', '1', '2', '3'];
        }
        else {
          this.checkList = [];
        }
      } else {
        if (this.checkList.length == 3) {
          const allCheck = this.checkList.findIndex(item => item == '0');
          if (allCheck != -1) {
            this.checkList.shift();
          }
          else {
            this.checkList.unshift('0');
          }
        }
      }
    },
    formatStatus(status) {
      if (status === 0) {
        return this.$t('新增')
      } else if (status === 1) {
        return this.$t('已上架')
      } else {
        return this.$t('已下架')
      }
    },
    init: function () {
      this.dataForm = this.$route.query.dataForm
      this.checkList = this.dataForm.ranges.map(item => item + '');
      // this.checkList = this.dataForm.ranges.join(',').split(',') || [];
      this.dialogFormVisible = this.$route.query.dialogFormVisible
      this.dialogStatus = this.$route.query.dialogStatus
    },
    getCategories() {
      listCategory().then(response => {
        this.categories = response.data.data.list
        if (this.dataForm.goodsValue && this.dataForm.goodsValue.length > 0) {
          let p = [];
          this.dataForm.goodsValue.forEach(goodsId => {
            this.categories.forEach(category => {
              if (category.children && category.children.length > 0) {
                category.children.forEach(item => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach(sub => {
                      if (sub.id == goodsId) {
                        let tmp = sub.id;
                        p.push(tmp)
                      }
                    })
                  }
                })
              }
            })
          })
          this.dataForm.goodsValue = p;
        }
      })
    },
    getLocations() {
      listLocationRegion().then(response => {
        this.locations = response.data.data.list
        if (this.dataForm.regions && this.dataForm.regions.length > 0) {
          let p = [];
          this.dataForm.regions.forEach(id => {
            this.locations.forEach(region => {
              if (region.children && region.children.length > 0) {
                region.children.forEach(item => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach(sub => {
                      if (sub.id == id) {
                        let tmp = sub.id;
                        p.push(tmp)
                      }
                    })
                  }
                })
              }
            })
          })
        }
      })

    },
    getGoods() {
      this.listLoading = true
      listGoods(this.listGoodsQuery).then(response => {
        this.goodsList = response.data.data.list.map(goods => {
          return {
            label: goods.name,
            key: goods.id
          }
        })
      }).catch(() => {
        this.list = []
      })
    },
    handleBack() {
      this.$router.push({ path: '/coupon/extenCoupon' })
    },
    uploadPicUrl: function (response) {
      this.dataForm.pictureUrl = response.data.url
    },
    handleGoodsPicRemove: function () {
      this.dataForm.pictureUrl = undefined
    },
    createData() {
      console.log('createData')
      if (this.checkList.length == 0) {
        this.$message.error(this.$t('请选择使用范围'));
        return;
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.discountType == 2) {
            let p = [];
            this.dataForm.goodsValue.forEach(goodsId => {
              p.push(goodsId[2])
            })
            this.dataForm.goodsValue = p;
          }
          if (this.dataForm.selectGoods.length != 0 && this.dataForm.goodsType === 2) {
            for (let i = 0; i < this.dataForm.selectGoods.length; i++) {
              this.dataForm.goodsValue[i] = this.dataForm.selectGoods[i]
            }
          }
          this.dataForm.ranges = this.checkList.length == 4 ? ['0'] : this.checkList;
          // this.dataForm.ranges = this.checkList.filter(item => item != 0).join(',');
          this.dataForm.surplus = this.dataForm.total
          this.dataForm.type = 3
          this.$router.push({ path: '/coupon/extenCoupon' })
          createCoupon(this.dataForm)
            .then(response => {
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('Coupon_creation_successful')
              })

            })
            .catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })
        }
      })
    },
    updateData() {
      console.log('updateData')
      if (this.checkList.length == 0) {
        this.$message.error(this.$t('请选择使用范围'));
        return;
      }
      this.$refs['dataForm'].validate(valid => {
        let p = [];
        if (valid) {
          if (this.dataForm.discountType == 2) {
            this.dataForm.goodsValue.forEach(goodsId => {
              p.push(goodsId)
            })
            this.dataForm.goodsValue = p;
          }
          if (this.dataForm.selectGoods.length != 0 && this.dataForm.goodsType === 2) {
            this.dataForm.goodsValue = [];
            for (let i = 0; i < this.dataForm.selectGoods.length; i++) {
              this.dataForm.goodsValue[i] = this.dataForm.selectGoods[i]
            }
          }
          this.dataForm.ranges = this.checkList.length == 4 ? ['0'] : this.checkList;
          // this.dataForm.ranges = this.checkList.filter(item => item != 0).join(',');
          this.dataForm.surplus = this.dataForm.total
          updateCoupon(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('Coupon_update_successful')
              })

              this.$router.push({ path: '/coupon/extenCoupon' })
            })
            .catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })
        }
      })
    },
  },
  computed:{
    typePage(){
      return this.dialogStatus == 'create'
    }
  }
}
</script>

<style scoped>

</style>
